import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog
} from 'antd-mobile'
import classNames from 'classnames'
import {
  getUserProfile,
  updateUserProfile,
  updateUserPhoto
} from '@/store/actions/profile'
import { logout } from '@/store/actions/login'
import styles from './index.module.scss'
import useInitState from '@/hooks/useInitState'
import React, { useRef, useState } from 'react'
import EditInput from './EditInput'
import { useDispatch } from 'react-redux'
import { AxiosError } from 'axios'
import EditList from './EditList'
import dayjs from 'dayjs'
import { useHistory } from 'react-router'

const Item = List.Item

type ShowInput = {
  type: '' | 'name' | 'intro'
  show: boolean
}

type ShowList = {
  type: '' | 'photo' | 'gender'
  show: boolean
}
const ProfileEdit = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const refFile = useRef<HTMLInputElement>(null)

  const { profile } = useInitState(getUserProfile, 'profile')
  const [showBirthday, setShowBirthday] = useState(false)
  const [showInput, setShowInput] = useState<ShowInput>({
    type: '',
    show: false
  })

  // 关闭修改昵称和简介的弹层
  const hideInput = () => {
    setShowInput({ type: '', show: false })
  }

  // 实现修改
  // 修改昵称，简介，性别
  const onUpdate = async (key: string, value: string) => {
    if (key === 'photo') {
      // 修改图片，要额外处理
      // 1. 打开文件选择对话框
      refFile.current!.click()
      return
    }
    try {
      // 完成具体的修改动作
      await dispatch(updateUserProfile(key, value))
      Toast.show({
        icon: 'success',
        content: '修改成功'
      })
      hideInput()
      hideList()
    } catch (err) {
      const error = err as AxiosError<{ message: string }>
      Toast.show({
        icon: 'fail',
        content: error.response!.data.message
      })
    }
  }

  // 用户在文件域中选中了图片
  const onChangePhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files && e.target.files[0]
    if (!file) return
    // 选中了图片

    // 文件上传
    const fd = new FormData()
    fd.append('photo', file)

    dispatch(updateUserPhoto(fd))

    hideList()
    Toast.show('修改成功')
  }

  const [showList, setShowList] = useState<ShowList>({
    type: '',
    show: false
  })

  // 关闭修改头像和性别的弹层
  const hideList = () => {
    setShowList({ type: '', show: false })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        <input type="file" ref={refFile} hidden onChange={onChangePhoto} />
        {/* 标题 */}
        <NavBar
          onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}>
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              onClick={() => setShowList({ type: 'photo', show: true })}
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={profile.photo} alt="" />
                </span>
              }
              arrow>
              头像
            </Item>
            <Item
              onClick={() => setShowInput({ type: 'name', show: true })}
              arrow
              extra={profile.name}>
              昵称
            </Item>
            <Item
              onClick={() => setShowInput({ type: 'intro', show: true })}
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {profile.intro}
                </span>
              }>
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              onClick={() => setShowList({ type: 'gender', show: true })}
              arrow
              extra={profile.gender ? '女' : '男'}>
              性别
            </Item>
            <Item
              onClick={() => setShowBirthday(true)}
              arrow
              extra={profile.birthday}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button
            className="btn"
            onClick={async () => {
              const result = await Dialog.confirm({
                content: '你确定要退出吗'
              })
              if (result) {
                // 退出
                Toast.show({ content: '确认', position: 'bottom' })
                dispatch(logout())
                history.replace('/login')
                Toast.show({ content: '退出成功' })
              } else {
                Toast.show({ content: '点击了取消', position: 'bottom' })
              }
            }}>
            退出登录
          </Button>
        </div>
      </div>
      {/* 修改名字和简介 */}
      <Popup destroyOnClose visible={showInput.show} position="right">
        <EditInput
          type={showInput.type}
          hideInput={hideInput}
          onUpdate={onUpdate}
        />
      </Popup>

      <Popup destroyOnClose visible={showList.show} position="bottom">
        <EditList
          type={showList.type}
          hideList={hideList}
          onUpdate={onUpdate}
        />
      </Popup>

      <DatePicker
        title="时间选择"
        visible={showBirthday}
        onClose={() => {
          setShowBirthday(false)
        }}
        value={new Date(profile.birthday)}
        max={new Date()}
        min={new Date('1900-01-01')}
        onConfirm={(val) => {
          Toast.show(val.toDateString())
          onUpdate('birthday', dayjs(val).format('YYYY-MM-DD'))
        }}
      />
    </div>
  )
}

export default ProfileEdit
